﻿using System.Linq;
using Example.Model;
using Example.Transports.Customer;
using Zero.Backend;

namespace Example.Handlers
{
    /// <summary>
    /// Handles message requests
    /// </summary>
    public class CustomerHandler :  IRequestHandler
    {
        public GetCustomersResponse GetCustomers(GetCustomers request)
        {
            using (var context = new ModelContext())
            {
                var response = new GetCustomersResponse
                                   {
                                       Customers = context.Customers.ToList()
                                   };

                return response;
            }
        }

        public SaveCustomerResponse SaveCustomer(SaveCustomer request)
        {
            var newItem = request.Customer;

            using (var context = new ModelContext())
            {
                if (request.Create)
                {
                    context.Customers.Add(request.Customer);
                }
                else
                {
                    var cust = context.Customers.Find(newItem.Id);

                    cust.Name = newItem.Name;
                    cust.Surname = newItem.Surname;
                    cust.BirthDate = newItem.BirthDate;
                }

                context.SaveChanges();
            }

            return new SaveCustomerResponse { NewCustomerID = newItem.Id };
        }

        public GetCustomerResponse GetCustomer(GetCustomer request)
        {
            using (var context = new ModelContext())
            {
                var query = from c in context.Customers where c.Id == request.CustomerID select c;
                return new GetCustomerResponse { Customer = query.Single() };
            }
        }

        public DeleteCustomerResponse DeleteCustoemr(DeleteCustomer request)
        {
            using (var context = new ModelContext())
            {
                var customer = context.Customers.Find(request.CustomerID);
                context.Customers.Remove(customer);
                context.SaveChanges();
            }

            return new DeleteCustomerResponse();
        }
    }
}
